<script setup>
import { ref, computed, nextTick } from "vue";
import {
  PieChart as PieIcon,
  DataAnalysis,
  Warning,
  Money,
  TrendCharts
} from "@element-plus/icons-vue";
import BarChart from "@/components/charts/BarChart.vue";
import PieChart from "@/components/charts/PieChart.vue";
import LineChart from "@/components/charts/LineChart.vue";
import BudgetForm from "@/components/financial/BudgetForm.vue";

const barChartRef = ref(null);
const quarterChartRef = ref(null);
const pieChartRef = ref(null);
const trendChartRef = ref(null);

const budgetData = ref([
  { label: "年度总预算", value: 1850000, usageRate: 72, remaining: 518000 },
  { label: "园区维护", value: 450000, usageRate: 68, remaining: 144000 },
  { label: "员工工资", value: 800000, usageRate: 92, remaining: 64000 },
  { label: "能源消耗", value: 350000, usageRate: 85, remaining: 52500 },
  { label: "设备采购", value: 250000, usageRate: 45, remaining: 137500 },
]);

const monthlyExpenditure = ref({
  labels: Array.from({length: 12}, (_, i) => `${i+1}月`),
  datasets: [
    { label: "维护支出", data: [32, 28, 35, 40, 42, 38, 45, 50, 48, 52, 55, 60].map(v => v*1000) },
    { label: "能源支出", data: [45, 42, 38, 35, 40, 48, 55, 60, 58, 52, 50, 48].map(v => v*1000) },
    { label: "薪资支出", data: [65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65].map(v => v*1000) }
  ]
});

const quarterlyComparison = ref({
  labels: ["第一季度", "第二季度", "第三季度", "第四季度"],
  datasets: [
    { label: "2023年", data: [320, 380, 420, 480].map(v => v*1000) },
    { label: "2024年", data: [350, 400, 450, 520].map(v => v*1000) }
  ]
});

const categoryChartData = ref({
  labels: ["维护", "能源", "薪资", "设备", "办公", "其他"],
  datasets: [
    {
      data: [28, 25, 35, 8, 6, 8],
      backgroundColor: [
        "#FF6384", "#36A2EB", "#FFCE56", "#4BC0C0", "#9966FF", "#FF9F40"
      ],
    },
  ],
});

const costTrendData = ref({
  labels: ["2020", "2021", "2022", "2023", "2024"],
  datasets: [
    { label: "总成本", data: [120, 135, 145, 165, 185].map(v => v*10000) }
  ]
});

const aiSuggestions = ref([
  {
    title: "智能照明系统改造",
    description: "将传统照明更换为智能感应LED照明系统，预计可降低能耗30%",
    savingAmount: 85000,
    priority: "高",
    implementation: "3个月",
    roi: "1.2年"
  },
  {
    title: "空调系统优化",
    description: "安装智能温控系统，根据人流量和天气自动调节温度",
    savingAmount: 65000,
    priority: "高",
    implementation: "2个月",
    roi: "1.5年"
  },
  {
    title: "电子化办公推进",
    description: "全面推行无纸化办公，减少打印耗材使用",
    savingAmount: 32000,
    priority: "中",
    implementation: "1个月",
    roi: "0.8年"
  }
]);

const budgetOverview = computed(() => {
  const totalBudget = budgetData.value[0].value;
  const usedAmount = totalBudget * (budgetData.value[0].usageRate / 100);
  return {
    totalBudget,
    usedAmount,
    remaining: totalBudget - usedAmount,
    dailyBudget: (totalBudget - usedAmount) / 30
  };
});

const budgetDialogVisible = ref(false);
const activeExpenditureTab = ref("monthly");
const activeSuggestions = ref([0]);

const openBudgetDialog = () => {
  budgetDialogVisible.value = true;
};

const handleBudgetSubmit = (formData) => {
  budgetData.value = formData;
  budgetDialogVisible.value = false;
};

const getProgressStatus = (rate) => {
  return rate > 90 ? "exception" : rate > 75 ? "warning" : "success";
};

const formatCurrency = (value) => `¥${value.toLocaleString()}`;

const exportExcel = () => {
  ElMessage.success("导出Excel成功");
};

const exportPDF = () => {
  ElMessage.success("导出PDF成功");
};

const handleTabClick = () => {
  nextTick(() => {
    barChartRef.value?.resize();
    quarterChartRef.value?.resize();
    pieChartRef.value?.resize();
    trendChartRef.value?.resize();
  });
};
</script>


<template>
  <div class="budget-cost-management">
    <!-- 预算概览卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-statistic title="总预算" :value="budgetOverview.totalBudget" :formatter="formatCurrency">
          <template #prefix>
            <el-icon><Money /></el-icon>
          </template>
        </el-statistic>
      </el-col>
      <el-col :span="6">
        <el-statistic title="已使用" :value="budgetOverview.usedAmount" :formatter="formatCurrency">
          <template #prefix>
            <el-icon><TrendCharts /></el-icon>
          </template>
        </el-statistic>
      </el-col>
      <el-col :span="6">
        <el-statistic title="剩余预算" :value="budgetOverview.remaining" :formatter="formatCurrency" />
      </el-col>
      <el-col :span="6">
        <el-statistic title="日均可用" :value="budgetOverview.dailyBudget" :formatter="formatCurrency" />
      </el-col>
    </el-row>

    <!-- 预算规划模块 -->
    <section class="section budget-section">
      <div class="section-header">
        <h2>
          <el-icon><PieIcon /></el-icon> 预算规划
        </h2>
        <el-button type="primary" @click="openBudgetDialog">设置预算</el-button>
      </div>
      <el-divider />
      <div class="budget-planning">
        <el-row :gutter="20">
          <el-col :span="8" v-for="(item, index) in budgetData" :key="index">
            <el-card shadow="hover">
              <div class="budget-item">
                <div class="budget-header">
                  <span class="label">{{ item.label }}</span>
                  <el-tag :type="getProgressStatus(item.usageRate)" size="small">
                    {{ item.usageRate }}%
                  </el-tag>
                </div>
                <div class="budget-values">
                  <span class="total">总额: {{ formatCurrency(item.value) }}</span>
                  <span class="remaining">剩余: {{ formatCurrency(item.remaining || item.value * (100 - item.usageRate)/100) }}</span>
                </div>
                <el-progress
                  :percentage="item.usageRate"
                  :status="getProgressStatus(item.usageRate)"
                  :stroke-width="12"
                />
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </section>

    <!-- 支出分析模块 -->
    <section class="section expenditure-section">
      <h2>
        <el-icon><DataAnalysis /></el-icon> 支出分析
      </h2>
      <el-divider />
      <div class="expenditure-analysis">
        <el-tabs v-model="activeExpenditureTab">
          <el-tab-pane label="月度支出" name="monthly">
            <bar-chart :data="monthlyExpenditure" />
          </el-tab-pane>
          <el-tab-pane label="季度对比" name="quarterly">
            <bar-chart :data="quarterlyComparison" />
          </el-tab-pane>
          <el-tab-pane label="分类占比" name="category">
            <pie-chart :data="categoryChartData" />
          </el-tab-pane>
          <el-tab-pane label="成本趋势" name="trend">
            <line-chart :data="costTrendData" />
          </el-tab-pane>
        </el-tabs>
        <div class="export-actions">
          <el-button-group>
            <el-button @click="exportExcel">导出Excel</el-button>
            <el-button @click="exportPDF">导出PDF</el-button>
            <el-button type="primary">生成分析报告</el-button>
          </el-button-group>
        </div>
      </div>
    </section>

    <!-- 节约建议模块 -->
    <section class="section suggestion-section">
      <h2>
        <el-icon><Warning /></el-icon> 节约建议
      </h2>
      <el-divider />
      <div class="saving-suggestions">
        <el-collapse v-model="activeSuggestions" accordion>
          <el-collapse-item
            v-for="(suggestion, index) in aiSuggestions"
            :title="suggestion.title"
            :name="index"
            :key="index"
          >
            <div class="suggestion-detail">
              <p>{{ suggestion.description }}</p>
              <div class="suggestion-meta">
                <div>
                  <span>预计节省: {{ formatCurrency(suggestion.savingAmount) }}</span>
                  <el-tag size="small" class="ml-2">ROI: {{ suggestion.roi }}</el-tag>
                </div>
                <div>
                  <el-tag :type="suggestion.priority === '高' ? 'danger' : 'warning'" size="small">
                    {{ suggestion.priority }}优先级
                  </el-tag>
                  <el-tag type="info" size="small" class="ml-2">
                    实施周期: {{ suggestion.implementation }}
                  </el-tag>
                </div>
              </div>
              <el-button type="primary" size="small" class="mt-2">申请实施</el-button>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </section>

    <!-- 预算设置对话框 -->
    <el-dialog v-model="budgetDialogVisible" title="年度预算设置" width="50%">
      <budget-form :initialData="budgetData" @submit="handleBudgetSubmit" />
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
/* 优化后的样式 */
.budget-cost-management {
  padding: 20px;
  background-color: #f5f7fa;

  .section {
    background: white;
    padding: 24px;
    border-radius: 8px;
    margin-bottom: 24px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    &-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
    }

    h2 {
      display: flex;
      align-items: center;
      font-size: 18px;
      color: #303133;
      margin: 0;

      .el-icon {
        margin-right: 8px;
        font-size: 20px;
      }
    }
  }

  .budget-item {
    .budget-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .label {
        font-weight: bold;
        color: #303133;
        font-size: 15px;
      }
    }

    .budget-values {
      display: flex;
      justify-content: space-between;
      margin-bottom: 12px;
      font-size: 13px;

      .total {
        color: #606266;
      }

      .remaining {
        color: #67C23A;
        font-weight: 500;
      }
    }

    :deep(.el-progress) {
      margin-top: 8px;
      
      .el-progress-bar {
        padding-right: 0;
      }
    }
  }

  .export-actions {
    margin-top: 20px;
    text-align: right;
  }

  .saving-suggestions {
    .suggestion-detail {
      p {
        margin-bottom: 12px;
        line-height: 1.6;
        color: #606266;
      }

      .suggestion-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
        font-size: 13px;

        & > div {
          display: flex;
          align-items: center;
        }
      }
    }
  }

  .ml-2 {
    margin-left: 8px;
  }

  .mt-2 {
    margin-top: 8px;
  }
}
</style>